package com.huawei.api.builder;

import com.alibaba.fastjson.JSONObject;
import com.huawei.api.bean.FileInfo;
import com.huawei.api.exception.BaseCustomerException;
import com.huawei.api.utils.FileUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 加载配置的文件列表
 *
 * @since 2022/10/28
 */
@Data
public class FileCfgBuilder implements Builder {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileCfgBuilder.class);

    private final String fileCfgPath;

    private final FileInfo fileInfo;

    public FileCfgBuilder(String fileCfgPath, FileInfo fileInfo) {
        this.fileCfgPath = fileCfgPath;
        this.fileInfo = fileInfo;
    }

    @Override
    public void build() throws BaseCustomerException {
        boolean isExists = FileUtil.fileIsExists(fileCfgPath);
        if (isExists) {
            loadConfigFiles();
        }
    }

    /**
     * 如果配置中配置了检测文件信息，则不按照命令行的参数，以配置文件为准
     */
    private void loadConfigFiles() throws BaseCustomerException {
        try {
            String content = FileUtil.getFileContent(fileCfgPath);
            if (StringUtils.isBlank(content)) {
                return;
            }
            FileInfo fileInfo = JSONObject.parseObject(content, FileInfo.class);
            // 配置文件中的检测文件夹和检测文件如果都为空则按照命令行的参数为准,反之以配置文件为准
            if (fileInfo != null && (StringUtils.isNotBlank(fileInfo.getSource()) || StringUtils.isNotBlank(fileInfo.getIncludeFiles()))) {
                this.fileInfo.setSource(fileInfo.getSource());
                this.fileInfo.setIncludeFiles(fileInfo.getIncludeFiles());
                this.fileInfo.setExcludeFiles(fileInfo.getExcludeFiles());
            }
        } catch (BaseCustomerException exception) {
            LOGGER.debug("some error occur in custom language config builder");
            throw new BaseCustomerException("load custom rule config error");
        }
    }
}
